<template>
  <div class="login-container">
    <!-- 左侧扫码登录区域 -->
    <div class="login-left">
      <div class="login-content">
        <h1 class="login-title">智聘企业后台系统</h1>
        
        <div class="qr-container">
          <div class="qr-wrapper">
            <canvas ref="qrCanvas" class="qr-code"></canvas>
            <!-- 蒙层 -->
            <div v-if="showOverlay" class="qr-overlay">
              <div class="overlay-content">
                <p>{{ overlayText }}</p>
              </div>
            </div>
          </div>
          
          <p class="qr-tip">
            打开智聘App，使用企业角色扫一扫即可进行登录
          </p>
        </div>
        
        <!-- 步骤说明 -->
        <div class="steps-container">
          <h3 class="steps-title">操作步骤</h3>
          <div class="steps-list">
            <div class="step-item">
              <span class="step-number">1</span>
              <span class="step-text">登录智聘APP</span>
            </div>
            <div class="step-item">
              <span class="step-number">2</span>
              <span class="step-text">点击[我的] -> 切换身份[我要招人-主动出击]</span>
            </div>
            <div class="step-item">
              <span class="step-number">3</span>
              <span class="step-text">点击[我的] -> 点击导航栏[扫一扫] 图标</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 右侧背景图片 -->
    <div class="login-right">
      <img src="../assets/images/login/login_page.jpg" alt="登录背景" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import QRCode from 'qrcode'
import { getLoginToken, checkCodeScanApi, checkPhoneLoginApi } from '../api/login'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/modules/user'
const router = useRouter()
const qrCanvas = ref(null)
const qrToken = ref('')
const refreshCount = ref(0)
const showOverlay = ref(false)
const overlayText = ref('')
let refreshTimer = null
let scanTimer = null
let confirmTimer = null
let scanPollCount = 0
let confirmPollCount = 0
const MAX_POLL_COUNT = 30
const useStore = useUserStore()
// 生成二维码
const generateQRCode = async (token) => {
  try {
    await QRCode.toCanvas(qrCanvas.value, token, {
      width: 200,
      margin: 0,
      color: {
        dark: '#2c3e50',
        light: '#ffffff'
      }
    })
  } catch (error) {
    ElMessage.error('生成二维码失败')
  }
}

// 获取token并生成二维码
const fetchTokenAndGenerateQR = async () => {
  try {
    const token = await getLoginToken()
    console.log("qrToken" );
    
    qrToken.value = token
    await generateQRCode(qrToken.value)
  } catch (error) {
    console.error('获取token失败:', error)
  }
}

// 自动刷新token
const startAutoRefresh = () => {
  refreshTimer = setInterval(async () => {
    refreshCount.value++
    if (refreshCount.value >= 3) {
      showOverlay.value = true
      overlayText.value = '请刷新页面后重新获取二维码'
      clearAllTimers()
    } else {
      await fetchTokenAndGenerateQR()
    }
  }, 60000)
}

// 轮询二维码是否被扫描
const startScanPolling = () => {
  scanPollCount = 0
  scanTimer = setInterval(async () => {
    scanPollCount++
    if (scanPollCount > MAX_POLL_COUNT) {
      showOverlay.value = true
      overlayText.value = '请刷新页面后重新获取二维码'
      clearAllTimers()
      return
    }
    try {
      const result = await checkCodeScanApi(qrToken.value)
      if (result === true) {
        // 停止二维码刷新和扫码轮询
        clearInterval(refreshTimer)
        refreshTimer = null
        clearInterval(scanTimer)
        scanTimer = null
        showOverlay.value = true
        overlayText.value = '请在手机端进行登录'
        // 开始轮询手机端是否确认登录
        startConfirmPolling()
      }
    } catch (error) {
      // 可以根据需要处理异常
    }
  }, 3000)
}

// 轮询手机端是否确认登录
const startConfirmPolling = () => {
  confirmPollCount = 0
  confirmTimer = setInterval(async () => {
    confirmPollCount++
    if (confirmPollCount > MAX_POLL_COUNT) {
      showOverlay.value = true
      overlayText.value = '请刷新页面后重新获取二维码'
      clearAllTimers()
      return
    }
    try {
      const result = await checkPhoneLoginApi(qrToken.value)
      if (result !== null && result !== undefined) {
        clearInterval(confirmTimer)
        confirmTimer = null
        overlayText.value = '登录成功！正在跳转...'
        console.log("result",result);
        
        useStore.loginSuccessAction(result.accessToken)
        
        router.push('/dashboard')
      }
    } catch (error) {
      // 可以根据需要处理异常
    }
  }, 3000)
}

function clearAllTimers() {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
  if (scanTimer) {
    clearInterval(scanTimer)
    scanTimer = null
  }
  if (confirmTimer) {
    clearInterval(confirmTimer)
    confirmTimer = null
  }
}

onMounted(async () => {
  await fetchTokenAndGenerateQR()
  startAutoRefresh()
  startScanPolling()
})

onUnmounted(() => {
  clearAllTimers()
})
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.login-left {
  flex: 1;
  background-color: #f5f7fa; /* 商务灰白色背景 */
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  min-width: 50%;
}

.login-content {
  text-align: center;
  max-width: 400px;
  width: 100%;
}

.login-title {
  color: #2d3748;
  font-size: 1.8rem;
  font-weight: 500;
  margin-bottom: 3rem;
  text-align: center;
  letter-spacing: 1px;
}

.qr-container {
  background-color: #ffffff;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.qr-wrapper {
  display: flex;
  justify-content: center;
  margin-bottom: 1.5rem;
  position: relative;
}

.qr-code {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 12px;
  background-color: white;
}

.qr-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  z-index: 10;
}

.overlay-content {
  text-align: center;
  color: white;
  padding: 1rem;
}

.overlay-content p {
  margin: 0;
  font-size: 1rem;
  font-weight: 500;
}

.qr-tip {
  color: #718096;
  font-size: 0.9rem;
  line-height: 1.5;
  margin: 0;
  text-align: center;
}

.steps-container {
  margin-top: 2rem;
}

.steps-title {
  color: #2d3748;
  font-size: 1.1rem;
  font-weight: 500;
  margin-bottom: 1rem;
  text-align: center;
}

.steps-list {
  text-align: left;
}

.step-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 0.8rem;
  gap: 0.8rem;
}

.step-item:last-child {
  margin-bottom: 0;
}

.step-number {
  background-color: #4a5568;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  font-weight: 500;
  flex-shrink: 0;
  margin-top: 0.1rem;
}

.step-text {
  color: #4a5568;
  font-size: 0.9rem;
  line-height: 1.4;
  flex: 1;
}

.login-right {
  flex: 1;
  overflow: hidden;
  min-width: 50%;
}

.login-right img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
  
  .login-right {
    display: none;
  }
  
  .login-left {
    flex: none;
    height: 100vh;
    min-width: 100%;
  }
}
</style> 